#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
国际化管理模块
处理多语言支持和翻译文件管理
"""

import json
import logging
import os
from pathlib import Path
from typing import Dict, Any, Optional
from PySide6.QtCore import QObject, Signal, QLocale

# 初始化日志记录器
logger = logging.getLogger("i18n")

# 支持的语言列表
SUPPORTED_LANGUAGES = {
    "auto": "跟随系统",
    "zh_CN": "简体中文", 
    "en_US": "English"
}

# 翻译文件目录
TRANSLATIONS_DIR = Path(__file__).parent.parent / "translations"


class I18nManager(QObject):
    """国际化管理器"""
    
    # 语言变更信号
    language_changed = Signal(str)
    
    _instance = None
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            cls._instance = super(I18nManager, cls).__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        """初始化国际化管理器"""
        if self._initialized:
            return
            
        super().__init__()
        self._initialized = True
        self._current_language = "auto"
        self._translations = {}
        self._load_all_translations()
        
    def _load_all_translations(self):
        """加载所有翻译文件"""
        try:
            # 确保翻译目录存在
            os.makedirs(TRANSLATIONS_DIR, exist_ok=True)
            
            # 加载每种语言的翻译文件
            for lang_code in ["zh_CN", "en_US"]:
                translation_file = TRANSLATIONS_DIR / f"{lang_code}.json"
                if translation_file.exists():
                    with open(translation_file, 'r', encoding='utf-8') as f:
                        self._translations[lang_code] = json.load(f)
                        logger.info(f"已加载 {lang_code} 翻译文件")
                else:
                    logger.warning(f"翻译文件不存在: {translation_file}")
                    self._translations[lang_code] = {}
                    
        except Exception as e:
            logger.error(f"加载翻译文件失败: {str(e)}")
            
    def get_supported_languages(self) -> Dict[str, str]:
        """获取支持的语言列表
        
        Returns:
            语言代码到显示名称的映射
        """
        return SUPPORTED_LANGUAGES.copy()
        
    def set_language(self, language_code: str):
        """设置当前语言
        
        Args:
            language_code: 语言代码 (auto, zh_CN, en_US)
        """
        if language_code not in SUPPORTED_LANGUAGES:
            logger.warning(f"不支持的语言代码: {language_code}")
            return
            
        old_language = self._current_language
        self._current_language = language_code
        
        if old_language != language_code:
            logger.info(f"语言已切换: {old_language} -> {language_code}")
            self.language_changed.emit(language_code)
            
    def get_current_language(self) -> str:
        """获取当前语言代码
        
        Returns:
            当前语言代码
        """
        return self._current_language
        
    def get_effective_language(self) -> str:
        """获取实际生效的语言代码
        
        Returns:
            实际语言代码 (不包含auto)
        """
        if self._current_language == "auto":
            # 根据系统语言自动选择
            system_locale = QLocale.system().name()
            if system_locale.startswith("zh"):
                return "zh_CN"
            else:
                return "en_US"
        return self._current_language
        
    def translate(self, key: str, default: str = None) -> str:
        """翻译文本
        
        Args:
            key: 翻译键
            default: 默认文本，如果翻译不存在
            
        Returns:
            翻译后的文本
        """
        effective_lang = self.get_effective_language()
        
        # 获取翻译
        if effective_lang in self._translations:
            translation = self._translations[effective_lang].get(key)
            if translation:
                return translation
                
        # 如果没有找到翻译，返回默认值或键名
        if default is not None:
            return default
        return key
        
    def tr(self, key: str, default: str = None) -> str:
        """翻译文本的简写方法
        
        Args:
            key: 翻译键
            default: 默认文本
            
        Returns:
            翻译后的文本
        """
        return self.translate(key, default)


# 导出单例实例
i18n = I18nManager()


def tr(key: str, default: str = None) -> str:
    """全局翻译函数
    
    Args:
        key: 翻译键
        default: 默认文本
        
    Returns:
        翻译后的文本
    """
    return i18n.translate(key, default) 